package com.example.dishchickenimageloader;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;

import java.lang.ref.WeakReference;

public class ImageLoader {


    private WeakReference<ImageView> imgRef = new WeakReference<>(null);
    private Bitmap currentBitmap;
    private final String TAG = "ImageLoader";
    private Activity activity;
    private static final MemoryCache MEMORY_CACHE = new MemoryCache(10);


    public static ImageLoader with(Activity activity) {
        ImageLoader imageLoader = new ImageLoader();
        imageLoader.activity = activity;
        return imageLoader;
    }


    /**
     * 当加载对象是网络图片
     */
    public ImageLoader load(String url) {
        Bitmap memoryCachedBitmap = MEMORY_CACHE.get(url);

        if (memoryCachedBitmap != null) {
            Log.e(TAG, "内存缓存命中");
            currentBitmap = memoryCachedBitmap;

        } else {
            Bitmap fileCachedBitmap = FileCache.get(url);
            if (fileCachedBitmap != null) {
                Log.e(TAG, "文件缓存命中");
                MEMORY_CACHE.put(url, fileCachedBitmap);//把位图放进内存缓存
                FileCache.remove(url);//把位图从文件缓存中删除
                currentBitmap = fileCachedBitmap;
                if(imgRef.get() != null) {
                    imgRef.get().setImageBitmap(currentBitmap);
                }

            } else {
                Log.e(TAG, "缓存未命中，开启网络请求");
                BitmapHttpUtil.getBitmap(url, new BitmapCallbackListener() {
                    @Override
                    public void onFinish(Bitmap bitmap) {
                        activity.runOnUiThread(() -> {
                            MEMORY_CACHE.put(url, bitmap);
                            if (imgRef.get() != null) {
                                imgRef.get().setImageBitmap(bitmap);
                            }
                        });
                    }

                    @Override
                    public void onError(Exception e) {
                        Log.e(TAG, "onError: " + e.getMessage());
                    }
                });
            }
        }
        return this;
    }


    /**
     * 当加载对象是drawable资源
     */
    public ImageLoader load(int resourceId) {
        currentBitmap = BitmapFactory.decodeResource(activity.getResources(), resourceId);
        return this;
    }


    public void into(ImageView imageView) {
        imgRef  = new WeakReference<>(imageView);
        if (currentBitmap != null) {
            imgRef.get().setImageBitmap(currentBitmap);
        }
    }
}
